import store from '../../service/store'
import axios from '../../plugins/axios'
import api from '../server'
import router from '../../router/index'

export function beforeRequest (config) {
  console.log('befere')
  console.log(config.url.indexOf('github_login'))
  if (store.getters.getAccessToken && config.url.indexOf('github_login') === -1) {
    config.headers = {
      ...config.headers,
      'access-token': store.getters.getAccessToken
    }
  }
  // 在发送请求之前做些什么
  return config
}
export function beforeRequestError (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
}

export function afterResponse (response) {
  let accessToken = response.data.token
  let refreshToken = response.data.refresh_token
  if (accessToken && refreshToken) {
    store.commit('login', response.data)
  }
  if (response.data && response.data.ret === -9998) {
    console.log('refresh_token也已经过期')
    return response
  } else if (response.data && response.data.ret === -9999) {
    console.log('token过期')

    let oldconfig = response.config
    let newconfig = {
      url: api.refresh_token,
      headers: {'refresh-token': store.getters.refreshToken}
    }
    console.log(newconfig)
    return axios.request(newconfig).then((res) => {
      if (res.data && res.data.ret === -9995) {
        localStorage.removeItem('accessToken')
        localStorage.removeItem('refreshToken')
        console.log('refresh_token也已经过期 跳转到登录页面')
        router.push({path: '/'})
        return res
      }
      let reconfig = {
        url: oldconfig.url,
        data: oldconfig.data
      }
      return axios.request(reconfig)
    })
  }
  // 对响应数据做点什么
  return response
}
export function afterResponseError (error) {
  // 对响应错误做点什么
  return Promise.reject(error)
}
